package com.tb.controller;

import com.tb.service.UserService;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService us;




    @PostMapping("/login")
    public ModelAndView login(String username,
                              String password,
                              ModelAndView mav,
                              HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("user", username);
        session.setMaxInactiveInterval(60 * 60 * 24);
        try {
            boolean flag = us.login(username, password);
            if (flag) {
                mav.setViewName("/index");
                mav.addObject("info", "登录成功");
                return mav;
            } else {
                mav.setViewName("/index");
                mav.addObject("info", "您还未登录");
                return mav;
            }
        } catch (UnknownAccountException e) {
            mav.setViewName("/login");
            mav.addObject("info", "用户名未找到！请检查！");
            return mav;
        } catch (IncorrectCredentialsException e) {
            mav.setViewName("/login");
            mav.addObject("info", "密码错误！请检查！");
            return mav;
        } catch (Exception e) {
            mav.setViewName("/login");
            mav.addObject("info", "服务器异常了！请检查！");
            return mav;
        }
    }

    @GetMapping("/loginOut")
    public ModelAndView loginOut(ModelAndView mav, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        try {
            us.loginOut();
            mav.setViewName("/login");
            mav.addObject("info", "成功退出！期待您回来");
            return mav;
        } catch (Exception e) {
            mav.setViewName("/login");
            mav.addObject("info", "服务器异常了，需要您再次确认");
            return mav;
        }
    }
}
